<#import "common/app-field.ftl" as fieldftl>   
<#assign entityName=root.entityName />  
<#assign formList=root.dataSource.formList/>
<#assign titleName=root.moduleProperties.caption/>
<#assign i18nKey=root.moduleProperties.i18nKey/>
<#assign moduleKey=root.moduleProperties.key/>

<#-- 判断是否有流程 -->
<#assign flowList= root.flowList />
<#assign isSelfApprove=true />
<#if flowList??&&flowList?size gt 0>
<#assign isSelfApprove=false />
</#if>


 <#list formList as form>  
 <#if form.isMaster == true>
 
    
	     	  
<template>
  <div  :style="contentStyle">     
       <wxc-minibar  v-if="isListEdit"
                       :title="checkTitle"
                      background-color="white"
                       left-text="取消"
                       :right-text="isCheckAll?'全不选':'全选'"
                        :use-default-return="false"
                        @wxcMinibarLeftButtonClicked="cancelListEdit"
                       @wxcMinibarRightButtonClicked="checkAll">
       </wxc-minibar>  
       <wxc-minibar     v-else 
                        :title="root['${i18nKey!titleName}']"
                        background-color="white"
                       :right-text="rightText"
                       @wxcMinibarRightButtonClicked="doAdd">
        </wxc-minibar>
      <div  class="tab">
      <div class="nav-cell"><text  class = "font-24">排序</text></div>
      <div class="nav-cell"  @click="dofilter"><text class = "font-24">筛选</text></div>
      </div>      
        <list  class="scroll-container" v-if="rows.length>0">
          <refresh class="refresh" @refresh="onrefresh" @pullingdown="onpullingdown" :display="refreshing ? 'show' : 'hide'">
            <loading-indicator class="indicator"></loading-indicator>
            <text class="indicator-text">重新加载 ...</text>
          </refresh>
          <cell    v-for="(item,index) in rows" :key ='index'   >
              <div    class="margin-10  light-bg">
                <wxc-cell  @wxcCellClicked = "doView(item.id,index)"  :title="item.createUser_caption||''"  :desc="item.createTime"  :has-arrow="true">
                  <text  slot="label"  style="margin-right:20px"  class="iconfont ">&#xe070;</text>
                  <wxc-tag   slot="value" type="solid" tag-color="#ff5000"  font-color="#ffffff" :value="item.status_caption"></wxc-tag>
                </wxc-cell>
               <div  class = "row padding-20  justify-between" @longpress="doListEdit" @click = "doView(item.id,index)">
                  <div  class="padding" @click = "doView(item.id,index)">                     
                  <#list form.fieldList as field>
                    <#if field.key??&&field.key!="">
                        <#assign queryProperties = field.queryProperties/>
                        <#if  queryProperties.showInGrid==true><#--列表显示-->
                            <div  class = "row margin-10">
                                    <text  class = "font-24">{{root['${field.i18nKey!field.caption}']}}</text>
                                    <text class = "font-24">:</text>
                                    <@fieldftl.getFieldView field = field />
                            </div>
                        </#if>
                    </#if>
                  </#list>        
                  </div>
                  <div  class="align-center"  > 
                    <div  v-if="isListEdit" > 
                          <!-- <input  @click="doItemClick(item,index)"  class="checkbox"  type="checkbox"  :value="index"   v-model="checkedItem"/>   -->
                          <qx-checkbox  ref='checkbox' :value="item"  @wxcCheckBoxItemChecked="wxcCheckBoxItemChecked"  :checked="false" >  </qx-checkbox>
                  
                    </div>
                  </div>
                </div>
              </div>
        </cell>
        <loading class="loading" @loading="onloading" :display="loadinging ? 'show' : 'hide'">
          <loading-indicator class="indicator"></loading-indicator>
          <text class="indicator-text">加载更多 ...</text>
        </loading>   
      </list>   
     <#-- 用弹层的办法打开 -->
     <#--  <wxc-popup
               popup-color="rgb(92, 184, 92)"
               :show="popupType!='nopopup'"
               pos="right">
      <div class="demo-content"  >      
               <view-page  v-if="popupType=='view'" :item="viewItem"  @closePage="closePage" @toEditPage="toEditPage" @doRefreshListPage = "doQuery"></view-page>
               <edit-page  v-if="popupType=='add'||popupType=='modify'" :popupType="popupType"  :item="editItem"  
               @doSaveEdit="doSaveEdit" @cancelEdit="cancelEdit"></edit-page>
      </div>
    </wxc-popup>    -->
     <view-page    ref="view-page"    @closePage="closePage" @toEditPage="toEditPage" @doRefreshListPage = "doQuery"></view-page>
     <edit-page    ref="edit-page"    @doSaveEdit="doSaveEdit" @cancelEdit="cancelEdit"></edit-page>
     <filter-page    ref="filter-page"   @doRefreshListPage = "doQuery"></filter-page>
     <div    v-if="isListEdit"  class="nav" ref="bottomNav" >
        <div v-for="(btn,index) in  bottomBtns " :key="index" class="nav-cell"  @click="bottomNavClick(btn.key)"><text class="font-24" >{{btn.text}}</text></div>
    </div>
      </div>
</template>

<script>
  import { WxcMinibar,WxcCell,WxcPopup,WxcTag  ,WxcButton,WxcSlideNav,Utils ,WxcIcon } from 'weex-ui';
  import { formatDate } from  '../../../filters';
  const modal = weex.requireModule('modal');
  import  i18nMdJson from  '../../../i18n/module/${moduleKey}' ;
  import  QxCheckbox from  '../../../components/qx-checkbox' ;
  import  ViewPage   from  './${moduleKey?lower_case}-view.vue';
  import  EditPage   from  './${moduleKey?lower_case}-edit.vue';
  import FilterPage  from  './${moduleKey?lower_case}-filter.vue';
  import jwpf from '../../../components/jwpf';
  import  {$curUserLoginName$,$curUserId$,$curOrgId$,$curOrgCode$,$curUserEmployeeId$,$curUserName$ }  from  '../../../components/systemVar'
  export default {
    components: { WxcCell,WxcMinibar,WxcPopup,WxcButton,WxcIcon,WxcTag   ,QxCheckbox,ViewPage,EditPage,FilterPage},
    data:()=>({   
        queryParams:{
            "rows" : 20,
            "page" : 1,
            "sort" : "id",
            "order" : "desc"
        },
        root:i18nMdJson,
        rows:[],
        curId:null,
        viewItem:null,
        editItem:null,
        popupType:'nopopup',
        curIndex:null,
        checkedItem:[],
        isCheckAll:false,
        checkedCount:0,
        isListEdit:false,
        Loop:null,
        checkedTag:null,
        entityName:'${entityName}',
        <#if ((form.referEntityTableName)!"")!="">
            referEntityTableName:'${form.referEntityTableName}',
        <#else>
             referEntityTableName:null,
         </#if>
        checked:false,
        resUrls:[],
        refreshing:false,
        loadinging:false,
        page:1
    }),
    created(){
        this.doQuery();
        this.checkResourceUrl();
        jwpf.setObj(this);
    },
    beforeUpdate(){
    },
    updated(){
        let cr = this.$router.currentRoute;
        if(cr) {
          var hs = cr.hash;
          if(hs) {
            let id = hs.slice(1);
            this.doView(parseInt(id),0);
          }
        }
    },
    computed:{
         checkTitle(){
           return  '已选中（'+this.checkedCount+")";
         },
         contentStyle(){
              const PageHeight = Utils.env.getPageHeight();
              let contentHeight  = PageHeight;
              <#--  if(this.isListEdit) {
                contentHeight=PageHeight-100;
                }else{
                  contentHeight = PageHeight
               }  -->
               return  { height: contentHeight + 'px' };                  
         },
         rightText(){
                  if(this.resUrls.indexOf('/gs/gs-mng!add.action?entityName=${entityName}')>=0){
                      return '新增';
                  }else{
                      return '';
                  }
         },
         bottomBtns(){
              let  bottomBtns = [];
                    if(this.resUrls.indexOf('/gs/gs-mng!delete.action?entityName=${entityName}')>=0)
                          bottomBtns.push({
                            icon:'',
                            text:'删除',
                            key:'doListDelete',
                            resourceUrl:'/gs/gs-mng!delete.action?entityName=${entityName}'
                          });
                  <#if  isSelfApprove==true>
                    if(this.resUrls.indexOf('/gs/process!startApprove.action?entityName=${entityName}')>=0)
                          bottomBtns.push({
                              icon: '',
                              text:'审核通过',
                              key:'doSelfProcess',
                              resourceUrl:'/gs/process!startApprove.action?entityName=${entityName}'
                          });
                      if(this.resUrls.indexOf('/gs/process!cancelApprove.action?entityName=${entityName}')>=0)
                          bottomBtns.push( {
                              icon: '',
                              text:'撤销审批',
                              key:'doCancelApproved',
                              resourceUrl:'/gs/process!cancelApprove.action?entityName=${entityName}'
                          });
                  </#if>               
              return  bottomBtns;
         }
    },
    methods: {
      onrefresh (event) {
        this.doQuery();
      },
      onpullingdown (event) {
        console.log("dy: " + event.dy)
        console.log("pullingDistance: " + event.pullingDistance)
        console.log("viewHeight: " + event.viewHeight)
        console.log("type: " + event.type)
      },
      onloading (event) {
        modal.toast({ message: 'Loading', duration: 1 })
        this.loadinging = true
        setTimeout(() => {
          this.loadinging = false
        }, 1000)
      },
      closePage(){
           this.popupOverlayBottomClick();

      },
      cancelListEdit(){
          this.isListEdit = false;
           this.checkedItem = [];
      },
      checkAll(){
               const {isCheckAll }  =this ;
               this.isCheckAll= !isCheckAll;
               this.$refs['checkbox'].forEach((el)=>{
                     el.innerChecked= this.isCheckAll;
                  });
              if(this.isCheckAll){           
                  this.checkedItem = JSON.parse(JSON.stringify(this.rows));
                  this.checkedCount=this.checkedItem.length;
              }else{
                  this.checkedItem = [];
                  this.checkedCount=0;
              }   
          
     },  
      wxcCheckBoxItemChecked(e){
          if (e.checked) {
            this.checkedItem.push(e.value);
          } else {
            const index = this.checkedItem.indexOf(e.value);
            this.checkedItem.splice(index, 1);
          }
          this.checkedCount = this.checkedItem.length;
      },
      doSelfProcess(){
          let ids = [];
          let rows = this.checkedItem;
          for(let i = 0;i<rows.length;i++){
            if(rows[i].status!='10'&&rows[i].status!='31'){
              this.alert("只有草稿状态的记录才可以进行该操作！");
              return;
            }
            ids.push(rows[i].id);
          }
          if(ids.length){
            this.confirm('确定要审核通过吗？审核通过后，该记录将不许修改和删除！',r=>{
              if(r){

              }
            })
          }
      },
      bottomNavClick(btnKey){
        if(this[btnKey]){
          this[btnKey]();
        }
      },
      //删除勾选的
      doListDelete(){         
          let ids = [];
          for(let i=0;i<this.checkedItem.length;i++){
            console.log(this.checkedItem[i]);
            if(this.checkedItem[i].status!='10'){
               this.alert("亲，非草稿状态的不能删除！");
               return;
            }
            ids.push(this.checkedItem[i].id);
          }
          if(ids!=null&&ids.length>0){
            this.confirm('确定要删除吗',r=>{
                 if(r){
                     this.sendRequest({
                       url:'/gs/gs-mng!delete.action?entityName='+(this.referEntityTableName?this.referEntityTableName:this.entityName),
                       data:{
                         'ids':ids
                       },
                       success:data=>{
                          if(data.msg){
                            this.doQuery();
                          }
                       },
                     })
                 }
            })
          }else{
            this.alert("请选择要删除的记录！");
          }
          
      },
      //列表编辑
      doListEdit(){           
              this.isListEdit = true;      
      },
      //新增
      doAdd(){
        this.$refs['edit-page'].show({type:"add"});       
      },     
       //保存修改
      doSaveEdit(e){
        let jsonSaveData = JSON.stringify(e.item);
        let params = {
          "jsonSaveData":jsonSaveData
        };
        this.sendRequest({
          "url":"/gs/gs-mng!save.action?entityName="+(this.referEntityTableName?this.referEntityTableName:this.entityName),
          "data":params,
          "success":data=>{
              if(data.flag==1){                    
                 this.doQuery();                  
                 this.$refs['edit-page'].show({type:"close"});
                 this.$refs['view-page'].show({id:data.msg.id,status:true,item:data.msg})
		             modal.toast({
		                      message:'保存成功！'
		             });
		               
              }else{
              }

          }
        })
      },
      //通过id查找
      queryEntity(id,callFunc){
          let options = {
            url:'/gs/gs-mng!queryEntity.action?entityName='+(this.referEntityTableName?this.referEntityTableName:this.entityName)+'&relevanceModule=',
            data:{
              'id':id
            },
            success:data=>{ 
                if (callFunc)           
                callFunc(data.msg);           
            }
          }
          this.sendRequest(options);
      },
      //取消编辑
      cancelEdit(){
          if(this.popupType=='add'){
            this.popupType='nopopup'
          }else if(this.popupType='modify'){
            this.popupType="view";
          }
      },
      //修改
      toEditPage(e){
          this.$refs['edit-page'].show(e);
      },
      //字段显示值初始化
     initFieldCaption(){
 
	      <#list form.fieldList as field>
	      <#if field.key!="">	          
		      <@fieldftl.initFieldCaption field = field />
		    </#if>
	      </#list>
     },    
      //查看
      doView(id,index){
        if(!this.isListEdit){
          this.curId = id;
          this.curIndex=index; 
          this.$refs['view-page'].show({status:true,id:id,callback:null});
        }
      }, 
      //非状态组件，需要在这里关闭
      popupOverlayBottomClick () {
        this.popupType = "nopopup";
        this.curIndex = null;
      },
      wxcCellClicked (e) {
        console.log(e)
      },
      minibarLeftButtonClick(e){ 
        modal.toast({message:"left"});
      },
      minibarRightButtonClick(e) {
        modal.toast({message:"right"});
      },
      doQuery(e){
        this.refreshing = true;
        if(e&&e.filterParams){
           this.queryParams = this.extend(this.queryParams,e.filterParams);
        }
        this.sendRequest({
    			"url" : "/gs/gs-mng!queryList.action?entityName="+(this.referEntityTableName?this.referEntityTableName:this.entityName), // servlet请求地址
    			"data" : this.queryParams , // action对应的参数
    			"success" : data=> {
                 this.rows =   data.rows; 
                 this.isListEdit = false;  
                 this.refreshing = false;            
          }
    	});
      },
      dofilter(){
        this.$refs['filter-page'].show();
      },
      checkResourceUrl(){
         this.getCache("_resource_url_").then(res=>{
            if(res&&res.length>0){
              this.resUrls=res;
            }else{
              this.jump('/');
            }
         });
      }
    },
    filters: {
    capitalize (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    },
    formatDate(time) {
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd');
    }
    }
  };
</script>

<style scoped>
  .nav {
    left: 0;
    flex-direction: row;
    align-items: center;
    border-top-color:#e0dddd;
    border-top-style:ridge ;
    border-top-width:2px;
    bottom: 0;
    height:100px;
  }
  .nav-cell {
    flex: 1;
    background-color: #ffffff;
    align-items: center;
    justify-content: center;
    height:60px;
  }
  .nav-cell:active{
     background-color:#00BDFF;
  }

  .scroll-container {
    background-color: #f2f3f4;
    flex: 1;
  }

  .shadow {
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  }

  .shadow:active {
    box-shadow: inset 0 5px 10px rgba(0, 0, 0, 0.2);
  } 

  .item-container:active {
     background-color: #00BDFF;
   }
  
  .item-row{
     flex-direction: row;
   }
  


  .tab{
    border-bottom-color:#e0dddd;
    border-bottom-style:ridge ;
    border-bottom-width: 2px;
    height:70px;
    flex-direction:row;
    background-color:white;
    justify-content:space-between;
    padding:5px;
  }

  .body-container {  
    background-color: #f2f3f4;
  }
  
  .loading {
    width: 750;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
  }
  .refresh {
    width: 750;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
  }
  .indicator-text {
    color: #888888;
    font-size: 24px;
    text-align: center;
  }
  .indicator {
    margin-top: 16px;
    height: 60px;
    width: 60px;
    color: blue;
  }
  .iconfont {
    font-family:iconfont;  
  }
  
  .font-24{
    font-size: 24px;
  }

</style>
<style src='../../../style/main.css' />
</#if>
</#list>
